<?php
/*******************************************************************************
 * @author      -> Mattia Leonardo Angelillo
 * @email       -> mattia.angelillo@gmai.com
 * @version     -> 1.0 stable
 * 
 * @desctiption -> Gestione di un calendario con gestione di eventi selezionando
 *                  le date da database.
*******************************************************************************/

class Calendar{
    ///Next - prev
    public $nextMonth;
    public $prevMonth;
    public $nextYear;
    public $prevYear;
    //Current
    public $currentMonth;
    public $currentNameMonth;
    public $currentDay;
    public $currentYear;
    public $daysOfWeek = array(
        'it' => array(
            'sunday'    => 'Domenica',
            'monday'    => 'Luned&igrave;',
            'tuesday'   => 'Marted&igrave;',
            'wednesday' => 'Mercoled&igrave;',
            'thursday'  => 'Gioved&igrave;',
            'friday'    => 'Venerd&igrave;',
            'saturday'  => 'Sabato',
        ),
        'en' => array(
            'monday'    => 'Monday',
            'tuesday'   => 'Tuesday',
            'wednesday' => 'Wednesday',
            'thursday'  => 'Thursday',
            'friday'    => 'Friday',
            'saturday'  => 'Saturday',
            'sunday'    => 'Sunday',
        ),
    );
    public $nameOfMounth = array(
        'it' => array(
            'january'   => 'Gennaio',
            'february'  => 'Febbraio',
            'march'     => 'Marzo',
            'april'     => 'Aprile',
            'may'       => 'Maggio',
            'june'      => 'Giugno',
            'july'      => 'Luglio',
            'august'    => 'Agosto',
            'september' => 'Settembre',
            'october'   => 'Ottobre',
            'november'  => 'Novembre',
            'december'  => 'Dicembre'
        ),
        'en' => array(
            'january'   => 'January',
            'february'  => 'February',
            'march'     => 'March',
            'april'     => 'April',
            'may'       => 'May',
            'june'      => 'June',
            'july'      => 'July',
            'august'    => 'August',
            'september' => 'September',
            'october'   => 'October',
            'november'  => 'November',
            'december'  => 'December'
        ),
    );
    public $day_total;
    
    //Database
    public $connection;
    public $dates;
    public $table;
    public $dataColumn;
    //Language
    private $lang='it';
    
    public function __construct($lang = 'it', Array $database=array()) {
        $this->database($database);//Database's connection
        
        $this->lang         = $lang;
        $this->currentDay   = date("d");
        $this->currentYear  = date("Y");
        if(isset($_GET['month'])){
            $month = $_GET['month'];
            $year = $_GET['year'];
            
            $this->nextYear = $_GET['year'];
            $this->prevYear = $_GET['year'];
            $this->prevMonth    = $month-1;
            $this->nextMonth    = $month+1;
            
            if($_GET['action']=='next'){
                if(($month%12)==0){
                    $this->nextMonth    = 1;
                    $this->prevMonth    = 11;
                    $this->nextYear     ++;
                    //$this->nextYear     = $_GET['year']+1;
                }
                if($month==1){
                    $this->prevMonth    = 12;
                    $this->prevYear --;
                }
            }
            if($_GET['action']=='prev'){
                if($month==1){
                    $this->prevMonth    = 12;
                    $this->nextMonth    = 1;
                    $this->prevYear --;
                    $this->nextYear ++;
                }
                if($month==12){
                    $this->nextMonth = 1;
                    $this->nextYear     ++;
                }
            }
            
            $this->currentMonth = date("n", mktime(0, 0, 0, $month, 1, $year));
            $this->currentYear = $year;
        }else{
            $this->prevMonth    = date("n")-1;
            $this->nextMonth    = date("n")+1;
            $this->currentMonth = date("n", mktime(0, 0, 0, date("n"), 1, date("Y")));
        }
        $this->day_total    = cal_days_in_month(CAL_GREGORIAN, $this->currentMonth, $this->currentYear);
    }

    protected function database(Array $database){
        if(count($database)!=0){
            if(isset($database['connection'])){
                $this->connection = $database['connection'];
                if(isset($database['table'])){
                    $this->table = $database['table'];
                    if(isset($database['datacolumn'])){
                        $this->dataColumn = $database['datacolumn'];
                        
                        //Trovo le date occupate
                        $sql = "SELECT ".$this->dataColumn.
                                " FROM ".$this->table;
                        
                        $result = mysqli_query($this->connection, $sql);
                        $i=0;
                        while($rows = mysqli_fetch_row($result)){
                            /*echo $rows[0];
                            echo "<br>";*/
                            
                            $this->dates[$i] = $rows[0];
                            $i ++;
                        }
                    }
                }
            }
        }
    }

    protected function link(){
        if(count($_GET) == 0) return false;
        
        $link = "?";
        foreach($_GET as $key => $value){
            if($key!="action"&&$key!="month"&&$key!="year"){
                $link .= "$key=$value&";
            }
        }
        
        return $link;
    }
    
    protected function ations($action){
        $link = "";
        if(!$this->link()) $link = "?";
            
        if($action == "prev")
            return $link.$this->link()."month=".$this->prevMonth."&action=prev&year=".($this->prevYear);
        else
            return $link.$this->link()."month=".$this->nextMonth."&action=next&year=".($this->nextYear);
    }

    public function calendar(){
        $pre    = $this->ations('prev');
        //echo "<br>";
        $next   = $this->ations('next');
        
        $month = $this->currentMonth;
        $monthTitleKey = strtolower(date("F", mktime(0, 0, 0, $month, 1, 0)));
        $year = $this->currentYear;
        
        $time =  mktime(0,0,0, $month, 1, $year);
        $date = getdate($time);
        $now = getdate(time());
        
        //Calendario
        echo "<div id='calendar'>";
            echo "<table>";

                echo "<tr>";
                    echo "<th colspan=7>";
                        echo "<div class='prev'>";
                        echo "<a href='$pre'><<</a>";
                        echo "</div>";
                        
                        echo "<div class='title'>";
                        echo $this->nameOfMounth[$this->lang][$monthTitleKey]." ".$this->currentYear;
                        echo "</div>";
                        
                        echo "<div class='next'>";
                        echo "<a href='$next'>>></a>";
                        echo "</div>";
                    echo "</th>";
                echo "</tr>";

                echo "<tr>";
                    //Giorni della settimana
                    foreach ($this->daysOfWeek[$this->lang] as $key => $value){
                        echo "<th>";
                        echo substr($value, 0, 3);
                        echo "</th>";
                    }
                echo "</tr>";

                for($i=0;$i<7;$i++){
                    echo '<tr>';
                    for ($j = 1; $j <= 7; $j++)
                    {
                        $day_number = $j + $i*7 - $date['wday'];
                        //stampa la cella con il giorno
                        echo '<td';
                        if ($day_number > 0 AND $day_number <= $this->day_total)
                        {
                            foreach ($this->dates as $key => $value){
                                //echo $value."<br>";
                                list($yy, $mm, $gg) = explode("-", $value);
                                //echo $timestamp = mktime(0, 0, 0, $mm, $gg, $yy);
                                
                                //echo "<p>$gg == $day_number</p>";
                                //Se il giorno è quello attuale e la data è occupata per un evento
                                if(($gg == $day_number && $mm == $date['mon'] && $yy == $date['year']) && ($day_number == $now['mday'] AND $month == $now['mon'] AND $year == $now['year'])){
                                    echo " class='onbusy this'";
                                //Altrimenti se il giorno è un evento
                                }elseif($gg == $day_number && $mm == $date['mon']) echo " class='onbusy'";
                            }
                            
                            //Data odierna
                            if ($day_number == $now['mday'] AND $month == $now['mon'] AND $year == $now['year'])
                            {
                                //echo " style=\"border: 1px solid #cc0000;\" ";
                                echo " class='this'";
                            }
                            /*if ($day_number == $now['mday'] AND $month == $now['mon'] AND $year == $now['year'])
                            {
                                echo " class='this'";
                            }*/
                                echo ">$day_number";
                        }else{
                            //stampa una cella vuota se non esiste il giorno
                            echo '> ';
                        }
                        echo '</td>';
                    }
                    echo "</tr>\n";
                    if ($day_number >= $this->day_total AND $i != 6)
                        break;
                     }
            echo "</table>";
            
            echo "<div class='legend'>\n";
                echo "\t<div class='busy'>";
                    echo "\t\t<div class='circle'></div>\n";
                    echo "\t\t<div class='title'>Data occupata</div>\n";
                echo "\t</div>\n";

                echo "\t<div class='now'>";
                    echo "\t\t<div class='circle'></div>\n";
                    echo "\t\t<div class='title'>Oggi</div>\n";
                echo "</div>\n";

            echo "\t</div>\n";
        echo "</div>";
    }
}